package com.jiusit.onePurchase.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ProcessBuilder.Redirect;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.stream.FileImageInputStream;

import org.apache.commons.lang3.RandomUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.jiusit.common.utils.User;
import com.jiusit.common.utils.UserWapper;
import com.jiusit.common.utils.Friendships;
import com.jiusit.common.utils.PostParameter;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.Render;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jiusit.common.utils.DataCoding;
import com.jiusit.common.utils.DateUtil;
import com.jiusit.common.utils.FileUtil;
import com.jiusit.common.utils.HttpClient;
import com.jiusit.common.utils.Paging;
import com.jiusit.common.utils.Response;
import com.jiusit.common.utils.StringUtil;
import com.jiusit.common.utils.TicketUtils;
import com.jiusit.common.utils.URLEncodeUtils;
import com.jiusit.common.utils.Upload;
import com.jiusit.common.utils.WeiboException;
import com.jiusit.onePurchase.interceptor.UserInterceptor;
import com.jiusit.onePurchase.model.ChampionCity;
import com.jiusit.onePurchase.model.ChampionCompetition;
import com.jiusit.onePurchase.model.ChampionCountryMedal;
import com.jiusit.onePurchase.model.ChampionEuropeCompetition;
import com.jiusit.onePurchase.model.ChampionEuropeGuessing;
import com.jiusit.onePurchase.model.ChampionEuropeTeam;
import com.jiusit.onePurchase.model.ChampionPocket;
import com.jiusit.onePurchase.model.ChampionPocketRandom;
import com.jiusit.onePurchase.model.ChampionPrizes;
import com.jiusit.onePurchase.model.ChampionRobPocket;
import com.jiusit.onePurchase.model.ChampionStartCurrencyRecord;
import com.jiusit.onePurchase.model.ChampionStartList;
import com.jiusit.onePurchase.model.ChampionUser;
import com.jiusit.onePurchase.model.ChampionUserCurrencyRecord;
import com.jiusit.onePurchase.model.ChampionUserExchang;
import com.jiusit.onePurchase.model.ChampionUserGuessing;
import com.jiusit.onePurchase.model.ChampionUserInvite;
import com.jiusit.onePurchase.model.ChampionUserMessage;
import com.jiusit.onePurchase.model.ChampionUserRun;
import com.jiusit.onePurchase.model.ChampionUserShare;
import com.jiusit.onePurchase.model.ChampionUserSign;
import com.jiusit.onePurchase.model.ChampionUserVisit;
import com.jiusit.onePurchase.model.ChampionWinnerGuessing;
import com.jiusit.onePurchase.model.WbKey;
import com.jiusit.onePurchase.model.WbVar;

@ControllerBind(controllerKey = "/home", viewPath = "/pages")
@Before(UserInterceptor.class)
/** 
 * 说明： 
 * 
 * @author  王汝绘 
 * @version 创建时间：2016年3月30日 上午11:13:40 
 */
/*
 * 首页
 */
public class HomeController extends ApiController {
	private static final Logger log = Logger.getLogger(HomeController.class);
	HttpClient client = new HttpClient();

	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		HttpClient client = new HttpClient();
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
	public void homePage() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			    //用户信息
			    ChampionUser championUser=ChampionUser.dao.findFirst("select * from champion_user where wb_id='"+xy_openid+"'");
			    setAttr("championUser", championUser);
			    //城市信息
			    List<ChampionCity> championCityList=ChampionCity.dao.find("select * from champion_city where 1=1");
			    setAttr("championCityList", championCityList);
			    render("index.html");
			
		} else {
			String url=getRequest().getRequestURI();
			System.out.println("url"+url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			setAttr("url", url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			render("error.html");
		}
	}


	public void init() {
		String reqUrl = getPara("reqUrl");
		Map dataMap = TicketUtils.getTicket();
		String js_ticket = dataMap.get("js_ticket").toString();
		UUID uuid = UUID.randomUUID();
		int random = RandomUtils.nextInt(1, 100);
		String noncestr = uuid.toString().replace("-", "");
		String timestamp = Long.toString(System.currentTimeMillis() / 1000
				+ random);
		String signStr = new StringBuilder().append(
				"jsapi_ticket=" + js_ticket + "&noncestr=" + noncestr
						+ "&timestamp=" + timestamp + "&url=" + reqUrl)
				.toString();
		log.debug("sign string=" + signStr);
		signStr = HashKit.sha1(signStr);
		log.debug("jssdk sign=" + signStr);
		Map wxConfig = new HashMap();
		wxConfig.put("appId", getApiConfig().getAppId());
		wxConfig.put("nonceStr", noncestr);
		wxConfig.put("timestamp", timestamp);
		wxConfig.put("signature", signStr);
		wxConfig.put("callback", reqUrl);
		wxConfig.put("js_ticket", js_ticket);
		renderJson(wxConfig);
	}

	// 获取奥运冠军榜
	public void getOlympicship() {
		 List<ChampionCountryMedal> championCountryMedalList=ChampionCountryMedal.dao.find("select @rownum:=@rownum+1 AS rownum,country_name,gold_number,silver_number,bronze_number,total_number from champion_country_medal, (SELECT @rownum:=0) champion_country_medal WHERE @rownum<2");
		 render("ranking.html");
		
	}

	// 签到
	public void sign() {
		Map map = new HashMap();
		String dateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
		int weekDay = DateUtil.dayOfWeek(new Date());
		String yesterDayStr = DateUtil.formatDate(
				DateUtil.dateAdd(3, -1, new Date()), "yyyy-MM-dd");
		String week_index = "周日";
		weekDay = weekDay - 1;
		if (weekDay == 0) {
			weekDay = 7;
		}
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				int get_curry = 0;
				ChampionUserSign checkUserSign = ChampionUserSign.dao
						.findFirst("select * from champion_user_sign where user_id='"
								+ championUser.getStr("id")
								+ "' and sign_date='" + dateStr + "'");
				if (checkUserSign == null) {
					get_curry = championUser.getInt("energy_currency") + 100;
						ChampionUserSign championUserSign = ChampionUserSign.dao
								.set("id", StringUtil.getUUID())
								.set("user_id", championUser.getStr("id"))
								.set("sign_date", dateStr)
								.set("week_index", weekDay)
								.set("ip_address",
										IpKit.getRealIp(getRequest()))
								.set("create_by", championUser.getStr("id"))
								.set("create_name",
										championUser.getStr("user_name"))
								.set("create_date", new Date())
								.set("update_by", championUser.getStr("id"))
								.set("update_name",
										championUser.getStr("user_name"))
								.set("update_date", new Date())
								.set("remarks", "签到");
						championUserSign.save();
						Db.update("update champion_user set energy_currency=energy_currency+100 where id='"+championUser.getStr("id")+"'");
						ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
								.set("id", StringUtil.getUUID())
								.set("user_id", championUser.getStr("id"))
								.set("get_date", new Date())
								.set("get_type", "02")
								.set("energy_currency", 100)
								.set("type", "02")
								.set("create_by", championUser.getStr("id"))
								.set("create_name",
										championUser.getStr("user_name"))
								.set("create_date", new Date())
								.set("update_by", championUser.getStr("id"))
								.set("update_name",
										championUser.getStr("user_name"))
								.set("update_date", new Date())
								.set("remarks", "签到");
						currencyRecord.save();
						map.put("code", 0);
						map.put("msg", "签到成功");
						map.put("energy_currency", get_curry);
				} else {
					map.put("code", -3);
					map.put("msg", "已签到");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} 
	}

	// 邀请好友
	public void invitefriend() {
		String uid = getPara("uid");
		String access_token = getCookie("accessToken");
		Map map = new HashMap();
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("text", "xxxxxxx");
		dataMap.put("url", "http://wlanzy1518.6655.la/home/homePage");
		dataMap.put("invite_logo", "http://api.fansiji.com/dialog-fail_03.png");
		JSONObject jsonObj = new JSONObject(dataMap);
		String json;
		json = URLEncodeUtils.encodeURL(jsonObj.toString());
		Map<String, String> sendMap = new HashMap<String, String>();
		sendMap.put("access_token", access_token);
		sendMap.put("uid", uid);
		sendMap.put("data", json);
		try {
			Response respon = client.post(
					"https://m.api.weibo.com/2/messages/invite.json",
					new PostParameter[] { new PostParameter("uid", uid),
							new PostParameter("data", jsonObj.toString()) },
					access_token);
			map.put("code", 0);
			map.put("msg", "成功");
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("code", -1);
			map.put("msg", "请邀请互相私信过的互粉好友");

		}
		renderJson(map);

	}

	// 获取赛事
	public void getCompetition() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			ChampionCompetition championCompetition = ChampionCompetition.dao
					.findFirst("select a.*,b.team_pic as 'visiting_team_pic',c.team_pic as 'home_team_pic',CASE  WHEN (UNIX_TIMESTAMP(a.end_time)-UNIX_TIMESTAMP(NOW())) >0 THEN '1' ELSE '0' END AS 'is_guess' ,(select count(*) from champion_user_guessing where competition_id=a.id and  user_id='"
							+ championUser.getStr("id")
							+ "') as 'countNum' from champion_competition a left join champion_team c on c.id=a.home_team left join champion_team b on b.id=a.visiting_team where competition_status <>'05'  order by a.end_time desc");
			if (championCompetition != null) {
				ChampionUserGuessing championUserGuessing = ChampionUserGuessing.dao
						.findFirst("select team_type,pay_currency,win_currency from champion_user_guessing where user_id='"
								+ championUser.getStr("id")
								+ "' and competition_id='"
								+ championCompetition.getStr("id") + "'");
				setAttr("championUserGuessing", championUserGuessing);
			}
			setAttr("championCompetition", championCompetition);
			setAttr("server_uri", PropKit.get("server_uri"));
			render("vs.html");
		} else {
			render("error.html");
		}
	}

	// 赛事竞猜
	public void guessCompetition() {
		Map map = new HashMap();
		String competition_id = getPara("competition_id");
		String team_id = getPara("team_id");
		String xy_openid = getCookie("xy_openid");
		int pay_currency = getParaToInt("pay_currency");
		String pay_odds = getPara("pay_odds");
		String team_type = getPara("team_type");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("energy_currency") >= pay_currency) {
					ChampionCompetition championCompetition = ChampionCompetition.dao
							.findFirst("select * ,(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(NOW())) AS 'is_guess' from champion_competition where competition_status='01' and id='"
									+ competition_id + "' ");
					if (championCompetition.getLong("is_guess") > 0) {
						ChampionUserGuessing checkUserGuessing = ChampionUserGuessing.dao
								.findFirst("select * from champion_user_guessing where competition_id='"
										+ competition_id
										+ "' and  user_id='"
										+ championUser.getStr("id") + "'");
						if (checkUserGuessing == null) {
							String id = StringUtil.getUUID();
							ChampionUserGuessing championUserGuessing = ChampionUserGuessing.dao
									.set("id", id)
									.set("user_id", championUser.getStr("id"))
									.set("competition_id", competition_id)
									.set("team_id", team_id)
									.set("guess_date", new Date())
									.set("pay_odds", pay_odds)
									.set("pay_currency", pay_currency)
									.set("team_type", team_type)
									.set("guess_status", "01")
									.set("create_by", championUser.getStr("id"))
									.set("create_name",
											championUser.getStr("user_name"))
									.set("create_date", new Date())
									.set("update_by", championUser.getStr("id"))
									.set("update_name",
											championUser.getStr("user_name"))
									.set("update_date", new Date())
									.set("remarks", "周日竞猜");
							boolean is_sucess = championUserGuessing.save();
							int remain_energy_currency = championUser
									.getInt("energy_currency") - pay_currency;
							if (is_sucess) {
								BigDecimal get_energy_currency = new BigDecimal(
										pay_currency);
								if (team_type == "01") {
									get_energy_currency = get_energy_currency
											.multiply(championCompetition
													.getBigDecimal("home_odds"));
								} else {
									get_energy_currency = get_energy_currency
											.multiply(championCompetition
													.getBigDecimal("visiting_odds"));
								}

								Db.update("update champion_user set energy_currency=energy_currency-"
										+ pay_currency
										+ " where id='"
										+ championUser.getStr("id") + "'");
								ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
										.set("id", StringUtil.getUUID())
										.set("user_id",
												championUser.getStr("id"))
										.set("get_date", new Date())
										.set("get_type", "05")
										.set("energy_currency", pay_currency)
										.set("type", "01")
										.set("create_by",
												championUser.getStr("id"))
										.set("create_name",
												championUser
														.getStr("user_name"))
										.set("create_date", new Date())
										.set("update_by",
												championUser.getStr("id"))
										.set("update_name",
												championUser
														.getStr("user_name"))
										.set("update_date", new Date())
										.set("remarks", "周日竞猜消费");
								currencyRecord.save();
								Map dataMap = new HashMap();
								map.put("code", 0);
								map.put("msg", "竞猜成功");
								dataMap.put("remain_energy_currency",
										remain_energy_currency);
								dataMap.put("get_energy_currency",
										get_energy_currency);
								map.put("callBackData", dataMap);
							} else {
								map.put("code", -3);
								map.put("msg", "系统繁忙 请稍后再试");
							}

						} else {
							map.put("code", -1);
							map.put("msg", "已竞猜过");
						}
					} else {
						map.put("code", -3);
						map.put("msg", "下注时间已过，无法竞猜");
					}
				} else {
					map.put("code", -4);
					map.put("msg", "活力币不足");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}

		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
	}

	// 兑换活力币
	public void exchangCurrency() {
		Map map = new HashMap();
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("step_number") >= 200) {
					BigDecimal step_number = new BigDecimal(
							championUser.getInt("step_number"));
					BigDecimal energy_currency = step_number.divide(
							new BigDecimal(200), BigDecimal.ROUND_DOWN);
					BigDecimal real_energy_currency = energy_currency;
					BigDecimal surplus_step_number = step_number
							.divideAndRemainder(new BigDecimal(200))[1];
					Db.update("update champion_user set step_number="
							+ surplus_step_number.toString()
							+ ",energy_currency=energy_currency+"
							+ real_energy_currency.toString() + " where id='"
							+ championUser.getStr("id") + "'");
					ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
							.set("id", StringUtil.getUUID())
							.set("user_id", championUser.getStr("id"))
							.set("get_date", new Date())
							.set("get_type", "01")
							.set("energy_currency",
									real_energy_currency.toString())
							.set("type", "02")
							.set("create_by", championUser.getStr("id"))
							.set("create_name",
									championUser.getStr("user_name"))
							.set("create_date", new Date())
							.set("update_by", championUser.getStr("id"))
							.set("update_name",
									championUser.getStr("user_name"))
							.set("update_date", new Date())
							.set("remarks", "微博运动");
					currencyRecord.save();
					map.put("code", 0);
					map.put("msg", "兑换成功");
					map.put("myEnergyCurrency",
							real_energy_currency.add(
									new BigDecimal(championUser
											.getInt("energy_currency")))
									.toString());
					map.put("energy_currency", real_energy_currency.toString());
					map.put("surplus_step_number",
							surplus_step_number.toString());
				} else {

					map.put("code", -1);
					map.put("msg", "步数不足");
				}

			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}

		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
	}

	// 跳转到转盘
	public void forwardTurntable() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.findFirst("select a.*,b.prisze_pic,b.prisze as 'prizse_name' from champion_user_exchang a left join champion_prizes b on b.id=a.prize_id where a.user_id='"
								+ championUser.getStr("id")
								+ "' and a.exchang_result='01' and a.exchang_type='01' ");
				setAttr("championUserExchang", championUserExchang);
			}
			setAttr("server_uri", PropKit.get("server_uri"));
			setAttr("championUser", championUser);
			render("wheel.html");
		} else {
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			render("error.html");
		}
	}

	// 跳转到兑换页面
	public void forwardExchang() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.findFirst("select a.*,b.prisze,b.prisze as 'prizse_name' from champion_user_exchang a left join champion_prizes b on b.id=a.prize_id where a.user_id='"
								+ championUser.getStr("id")
								+ "' and a.exchang_result='01' and a.exchang_type='03' ");
				setAttr("championUserExchang", championUserExchang);
			}
			setAttr("championUser", championUser);
			render("game.html");
		} else {
			render("error.html");
		}
	}

	// 转盘兑换
	public void turntableExchang() {
		String xy_openid = getCookie("xy_openid");
		String access_token = getCookie("accessToken");
		String content = getPara("content");
		String pic = getPara("pic");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			WbVar key = WbVar.dao
					.findFirst("select * from wb_var where VAR_NAME='turntable_prize_num' ");
			String turntable_prize_num = key.getStr("VAR_VALUE"); // 奖品数量
			WbVar gl_key = WbVar.dao
					.findFirst("select * from wb_var where VAR_NAME='turntable_gv' ");
			String turntable_gv = gl_key.getStr("VAR_VALUE");// 转盘概率
			BigDecimal win_num = new BigDecimal(turntable_prize_num);
			win_num = win_num.multiply(new BigDecimal(turntable_gv));
			int random_num = Integer.parseInt(turntable_prize_num);
			int random = RandomUtils.nextInt(1, random_num + 1);
			String prizse_id = "";
			String exchang_id = "";
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("energy_currency") >= 10) {
					ChampionUserExchang checkUserExchang = ChampionUserExchang.dao
							.findFirst("select * from champion_user_exchang where exchang_type='01' and user_id='"
									+ championUser.getStr("id") + "' ");
					if (checkUserExchang == null) {
						if (random <= win_num.intValue()) {
							ChampionPrizes championPrizes = ChampionPrizes.dao
									.findFirst("select * from champion_prizes where  prisze_status='01' and prisze_type='01' and prisze_system_type='01' and prisze_num >=1 ORDER BY RAND() LIMIT 1 ");
							if (championPrizes != null) {
								if (championPrizes.getInt("prisze_num") >= 1) {
									Db.update("update champion_prizes set prisze_num=prisze_num-1 where id='"
										+ prizse_id + "'");
										exchang_id = StringUtil.getUUID();
										prizse_id = championPrizes.get("id");
										ChampionUserExchang championUserExchang = ChampionUserExchang.dao
												.set("id", exchang_id)
												.set("prize_id", prizse_id)
												.set("user_id",
														championUser
																.getStr("id"))
												.set("exchang_date", new Date())
												.set("exchang_type", "01")
												.set("exchang_result", "01")
												.set("is_send", "01")
												.set("real_name", "")
												.set("telephone", "")
												.set("address", "")
												.set("pay_account", "")
												.set("create_by",
														championUser
																.getStr("id"))
												.set("create_name",
														championUser
																.getStr("user_name"))
												.set("create_date", new Date())
												.set("update_by",
														championUser
																.getStr("id"))
												.set("update_name",
														championUser
																.getStr("user_name"))
												.set("update_date", new Date())
												.set("remarks",
														"恭喜"
																+ URLDecoder
																		.decode(championUser
																				.getStr("user_name"))
																+ "抽奖获得"
																+ championPrizes
																		.getStr("prisze"));
										boolean is_sucess = championUserExchang
												.save();
										if (is_sucess) {
											Db.update("update champion_user set energy_currency=energy_currency-10 where id='"
													+ championUser.getStr("id")
													+ "'");
										}

										map.put("code", 0);
										map.put("msg", "成功");
										map.put("exchang_id", exchang_id);
										map.put("prize_pic_url",
												PropKit.get("server_uri")
														+ championPrizes
																.getStr("prisze_pic"));
										map.put("prizse_id", prizse_id);
										map.put("prisze_position",
												championPrizes
														.getInt("prisze_position"));
										map.put("prizse_name",
												championPrizes.get("prisze"));
								} else {
									Db.update("update champion_user set energy_currency=energy_currency-10 where id='"
											+ championUser.getStr("id") + "'");
									map.put("code", 1);
									map.put("msg", "谢谢参与");
								}
							} else {
								Db.update("update champion_user set energy_currency=energy_currency-10 where id='"
										+ championUser.getStr("id") + "'");
								map.put("code", 1);
								map.put("msg", "谢谢参与");
							}
						} else {
							Db.update("update champion_user set energy_currency=energy_currency-10 where id='"
									+ championUser.getStr("id") + "'");
							map.put("code", 1);
							map.put("msg", "谢谢参与");
						}

					} else {
						Db.update("update champion_user set energy_currency=energy_currency-10 where id='"
								+ championUser.getStr("id") + "'");
						map.put("code", 1);
						map.put("msg", "谢谢参与");
					}
					ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
							.set("id", StringUtil.getUUID())
							.set("user_id", championUser.getStr("id"))
							.set("get_date", new Date())
							.set("get_type", "07")
							.set("energy_currency", 10)
							.set("type", "01")
							.set("create_by", championUser.getStr("id"))
							.set("create_name",
									championUser.getStr("user_name"))
							.set("create_date", new Date())
							.set("update_by", championUser.getStr("id"))
							.set("update_name",
									championUser.getStr("user_name"))
							.set("update_date", new Date())
							.set("remarks", "转盘抽奖");
					currencyRecord.save();
					map.put("myEnergyCurrency",
							championUser.getInt("energy_currency") - 10);
				} else {
					map.put("code", 3);
					map.put("msg", "活力币不足");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 兑换转盘奖品
	public void ExchangTurntablePrize() {
		String xy_openid = getCookie("xy_openid");
		String exchang_id = getPara("id");
		String realName = getPara("realName");
		String telephone = getPara("telephone");
		String address = getPara("address");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.set("id", exchang_id).set("real_name", realName)
						.set("telephone", telephone).set("address", address)
						.set("exchang_result", "02")
						.set("update_by", championUser.getStr("id"))
						.set("update_name", championUser.getStr("user_name"))
						.set("update_date", new Date());
				boolean is_sucess = championUserExchang.update();
				if (is_sucess) {
					map.put("code", 0);
					map.put("msg", "兑换成功");
				} else {
					map.put("code", -3);
					map.put("msg", "系统繁忙 请稍后再试");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 获取奖品栏信息
	public void getChampionPrizes() {
		String xy_openid = getCookie("xy_openid");
		String page = getPara("page");
		String type = getPara("type");
		if (StringUtil.isEmpty(page)) {
			page = "1";
		}
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.findFirst("select a.*,b.prisze_pic,b.prisze as 'prizse_name' from champion_user_exchang a left join champion_prizes b on b.id=a.prize_id where a.user_id='"
								+ championUser.getStr("id")
								+ "' and a.exchang_result='01' and a.exchang_type='03' ");
				setAttr("championUserExchang", championUserExchang);
			}
			setAttr("server_uri", PropKit.get("server_uri"));
			List<ChampionPrizes> championPrizes = ChampionPrizes.dao
					.find("select * from champion_prizes where prisze_type='03' and prisze_status='01'  order by prisze_num desc,need_currency asc ");
			if (StringUtil.isEqual(type, "1")) {
				Map<Object, Object> map = new HashMap<Object, Object>();
				setAttr("server_uri", PropKit.get("server_uri"));
				map.put("championPrizesList", championPrizes);
				renderJson(championPrizes);
			} else {
				setAttr("championUser", championUser);
				setAttr("energy_currency",
						championUser.getInt("energy_currency"));
				setAttr("server_uri", PropKit.get("server_uri"));
				setAttr("championPrizesList", championPrizes);
				render("gifts.html");
			}
		} else {
			render("error.html");
		}
	}

	// 兑换奖品
	public void exchangPrizes() {
		Map map = new HashMap();
		String xy_openid = getCookie("xy_openid");
		String access_token = getCookie("accessToken");
		String content = getPara("content");
		String pic = getPara("pic");
		String prize_id = getPara("prize_id");
		String real_name = getPara("real_name");
		String telephone = getPara("telephone");
		String address = getPara("address");
		if (!StringUtil.isEmpty(xy_openid) && !StringUtil.isEmpty(access_token)) {
			ChampionPrizes championPrizes = ChampionPrizes.dao
					.findFirst("select * from champion_prizes where id='"
							+ prize_id + "' ");
			if (championPrizes != null) {
				if (championPrizes.getInt("prisze_num") > 0) {
					ChampionUser championUser = ChampionUser.dao
							.findFirst("select * from champion_user where wb_id='"
									+ xy_openid + "'");
					if (championUser != null) {
						if (championUser.getInt("energy_currency") >= championPrizes
								.getInt("need_currency")) {
							Db.update("update champion_prizes set prisze_num=prisze_num-1 where id='"
									+ prize_id + "'");
							Db.update("update champion_user set energy_currency=energy_currency-"
									+ championPrizes.getInt("need_currency")
									+ " where id='"
									+ championUser.getStr("id")
									+ "'");
							String exchang_id = StringUtil.getUUID();
							ChampionUserExchang championUserExchang = ChampionUserExchang.dao
									.set("id", exchang_id)
									.set("user_id", championUser.getStr("id"))
									.set("prize_id", prize_id)
									.set("exchang_date", new Date())
									.set("exchang_type", "03")
									.set("exchang_result", "01")
									.set("is_send", "01")
									.set("real_name", "")
									.set("telephone", "")
									.set("address", "")
									.set("pay_account", "")
									.set("create_by", championUser.getStr("id"))
									.set("create_name",
											championUser.getStr("user_name"))
									.set("create_date", new Date())
									.set("update_by", championUser.getStr("id"))
									.set("update_name",
											championUser.getStr("user_name"))
									.set("update_date", new Date())
									.set("remarks",
											"恭喜"
													+ URLDecoder
															.decode(championUser
																	.getStr("user_name"))
													+ "获得"
													+ championPrizes
															.getStr("prisze"));
							championUserExchang.save();
							ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
									.set("id", StringUtil.getUUID())
									.set("user_id", championUser.getStr("id"))
									.set("get_date", new Date())
									.set("get_type", "04")
									.set("energy_currency",
											championPrizes
													.getInt("need_currency"))
									.set("type", "01")
									.set("create_by", championUser.getStr("id"))
									.set("create_name",
											championUser.getStr("user_name"))
									.set("create_date", new Date())
									.set("update_by", championUser.getStr("id"))
									.set("update_name",
											championUser.getStr("user_name"))
									.set("update_date", new Date())
									.set("remarks", "兑换奖品");
							boolean is_sucess = currencyRecord.save();
							if (is_sucess) {
								content = content.replaceAll("用户抽到的奖品",
										championPrizes.getStr("prisze"));
								try {
									Upload.uploadWb(pic, access_token, content);// 发微博
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} finally {
									map.put("code", 0);
									map.put("msg", "成功");
									map.put("exchang_id", exchang_id);
									map.put("prisze_pic",
											PropKit.get("server_uri")
													+ championPrizes
															.getStr("prisze_pic"));
									map.put("prizse_name",
											championPrizes.get("prisze"));
								}
							} else {
								map.put("code", -3);
								map.put("msg", "系统繁忙 请稍后再试");
							}

						} else {
							map.put("code", -6);
							map.put("msg", "活力币不足");
						}
					} else {
						map.put("code", -2);
						map.put("msg", "用户不存在");
					}
				} else {
					map.put("code", -5);
					map.put("msg", "奖品数量不足");
				}

			} else {
				map.put("code", -4);
				map.put("msg", "奖品不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 红包兑换
	public void pocketExchang() {
		String xy_openid = getCookie("xy_openid");
		String access_token = getCookie("accessToken");
		String content = getPara("content");
		String pic = getPara("pic");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			WbVar key = WbVar.dao
					.findFirst("select * from wb_var where VAR_NAME='pocket_prize_num' ");
			String pocket_prize_num = key.getStr("VAR_VALUE"); // 红包奖品数量
			WbVar gl_key = WbVar.dao
					.findFirst("select * from wb_var where VAR_NAME='pocket_gv' ");
			String pocket_gv = gl_key.getStr("VAR_VALUE");// 红包概率
			BigDecimal win_num = new BigDecimal(pocket_prize_num);
			win_num = win_num.multiply(new BigDecimal(pocket_gv));
			int random_num = Integer.parseInt(pocket_prize_num);
			int random = RandomUtils.nextInt(1, random_num + 1);
			String exchang_id = "";
			String prizse_id = "";
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("energy_currency") >= 15) {
					ChampionUserExchang checkUserExchang = ChampionUserExchang.dao
							.findFirst("select * from champion_user_exchang where exchang_type='02' and user_id='"
									+ championUser.getStr("id") + "' ");
					if (checkUserExchang == null) {
						if (random <= win_num.intValue()) {

							ChampionPrizes championPrizes = ChampionPrizes.dao
									.findFirst("select * from champion_prizes where prisze_status='01' and prisze_type='02' and prisze_system_type='01' and prisze_num >=1 ORDER BY RAND() LIMIT 1 ");
							if (championPrizes != null) {
								if (championPrizes.getInt("prisze_num") >= 1) {
									
										prizse_id = championPrizes.getStr("id");
										exchang_id = StringUtil.getUUID();
										ChampionUserExchang championUserExchang = ChampionUserExchang.dao
												.set("id", exchang_id)
												.set("prize_id", prizse_id)
												.set("user_id",
														championUser
																.getStr("id"))
												.set("exchang_date", new Date())
												.set("exchang_type", "02")
												.set("exchang_result", "01")
												.set("is_send", "01")
												.set("real_name", "")
												.set("telephone", "")
												.set("address", "")
												.set("pay_account", "")
												.set("create_by",
														championUser
																.getStr("id"))
												.set("create_name",
														championUser
																.getStr("user_name"))
												.set("create_date", new Date())
												.set("update_by",
														championUser
																.getStr("id"))
												.set("update_name",
														championUser
																.getStr("user_name"))
												.set("update_date", new Date())
												.set("remarks",
														"恭喜"
																+ URLDecoder
																		.decode(championUser
																				.getStr("user_name"))
																+ "获得"
																+ championPrizes
																		.getStr("prisze")
																+ "红包");
										boolean is_sucess = championUserExchang
												.save();
										if (is_sucess) {
											Db.update("update champion_user set energy_currency=energy_currency-15 where id='"
													+ championUser.getStr("id")
													+ "'");
											Db.update("update champion_prizes set prisze_num=prisze_num-1 where id='"
													+ prizse_id + "'");
											map.put("code", 0);
											map.put("msg", "成功");
											map.put("exchang_id", exchang_id);
											map.put("prize_pic_url",
													PropKit.get("server_uri")
															+ championPrizes
																	.getStr("prisze_pic"));
											map.put("prizse_id", prizse_id);
											map.put("prizse_name",
													championPrizes
															.getStr("prisze"));
										} else {
											map.put("code", -3);
											map.put("msg", "系统繁忙 请稍后再试");
										}
								} else {
									Db.update("update champion_user set energy_currency=energy_currency-15 where id='"
											+ championUser.getStr("id") + "'");
									map.put("code", 1);
									map.put("msg", "谢谢参与");
								}
							} else {
								Db.update("update champion_user set energy_currency=energy_currency-15 where id='"
										+ championUser.getStr("id") + "'");
								map.put("code", 1);
								map.put("msg", "谢谢参与");
							}
						} else {
							Db.update("update champion_user set energy_currency=energy_currency-15 where id='"
									+ championUser.getStr("id") + "'");
							map.put("code", 1);
							map.put("msg", "谢谢参与");
						}
					} else {
						Db.update("update champion_user set energy_currency=energy_currency-15 where id='"
								+ championUser.getStr("id") + "'");
						map.put("code", 1);
						map.put("msg", "谢谢参与");
					}
					ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
							.set("id", StringUtil.getUUID())
							.set("user_id", championUser.getStr("id"))
							.set("get_date", new Date())
							.set("get_type", "06")
							.set("energy_currency", 15)
							.set("type", "01")
							.set("create_by", championUser.getStr("id"))
							.set("create_name",
									championUser.getStr("user_name"))
							.set("create_date", new Date())
							.set("update_by", championUser.getStr("id"))
							.set("update_name",
									championUser.getStr("user_name"))
							.set("update_date", new Date())
							.set("remarks", "红包兑换");
					currencyRecord.save();
					map.put("myEnergyCurrency",
							championUser.getInt("energy_currency") - 15);
				} else {
					map.put("code", 3);
					map.put("msg", "活力币不足");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 跳转到红包查看页面
	public void forwardPocket() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.findFirst("select a.*,b.prisze from champion_user_exchang a left join champion_prizes b on b.id=a.prize_id where a.user_id='"
								+ championUser.getStr("id")
								+ "' and a.exchang_result='01' and a.exchang_type='02' ");
				setAttr("championUserExchang", championUserExchang);
			}
			setAttr("championUser", championUser);
			render("pocket.html");
		} else {
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			render("error.html");
		}
	}

	// 判断用户活力币是否足够
	public void checkUserCurrency() {
		String xy_openid = getCookie("xy_openid");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("energy_currency") >= 5) {
					map.put("code", 0);
					map.put("msg", "成功");
				} else {
					map.put("code", -1);
					map.put("msg", "活力币不足");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 兑换红包
	public void ExchangPocketPrize() {
		String xy_openid = getCookie("xy_openid");
		String exchang_id = getPara("id");
		String realName = getPara("realName");
		String telephone = getPara("telephone");
		String pay_account = getPara("pay_account");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.set("id", exchang_id).set("real_name", realName)
						.set("telephone", telephone)
						.set("pay_account", pay_account)
						.set("exchang_result", "02")
						.set("update_by", championUser.getStr("id"))
						.set("update_name", championUser.getStr("user_name"))
						.set("update_date", new Date());
				boolean is_sucess = championUserExchang.update();
				if (is_sucess) {
					map.put("code", 0);
					map.put("msg", "兑换成功");
				} else {
					map.put("code", -3);
					map.put("msg", "系统繁忙 请稍后再试");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}

		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
	}

	// 判断用户活力币是否足够
	@Clear
	public void forWardErrorHtml() {
		String open_type = getPara("open_type");
		if (StringUtil.isEqual(open_type, "1")) {
			render("sorry.html");
		} else {
			render("sorrypc.html");
		}
	}

	@Clear
	public void stationInf() {
		String xy_openid = getCookie("xy_openid");
		ChampionUser countUser = ChampionUser.dao
				.findFirst("SELECT FORMAT(COUNT(DISTINCT id),0) AS 'userNum',FORMAT(SUM(total_step_number),0) AS 'total_step' FROM `champion_user`");
		setAttr("countUser", countUser);
		render("iframe.html");

	}

	// 兑换奖品
	public void prizeExchange() {
		String xy_openid = getCookie("xy_openid");
		String exchang_id = getPara("exchang_id");
		String realName = getPara("real_name");
		String telephone = getPara("telephone");
		String address = getPara("address");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				ChampionUserExchang championUserExchang = ChampionUserExchang.dao
						.set("id", exchang_id).set("real_name", realName)
						.set("telephone", telephone).set("address", address)
						.set("exchang_result", "02")
						.set("update_by", championUser.getStr("id"))
						.set("update_name", championUser.getStr("user_name"))
						.set("update_date", new Date());
				boolean is_sucess = championUserExchang.update();
				map.put("code", 0);
				map.put("msg", "兑换成功");
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			render("error.html");
		}

	}

	// 获取跑酷H5数据
	@Clear
	public void getH5Data() {
		String callback = getPara("jsoncallback");
		String xy_openid = getPara("uid");
		String step_num = getPara("step_num");
		Map map = new HashMap();
		ChampionUser championUser = ChampionUser.dao
				.findFirst("select * from champion_user where wb_id='"
						+ xy_openid + "'");
		if (championUser != null) {
			if (new BigDecimal(step_num).intValue() >= 100) {
				ChampionUserCurrencyRecord checkcurrencyRecord = ChampionUserCurrencyRecord.dao
						.findFirst("select * from champion_user_currency_record where TO_DAYS(NOW())=TO_DAYS(get_date) and user_id = '"
								+ championUser.getStr("id")
								+ "'  and get_type = '08' and type='02'  ");
				if (checkcurrencyRecord == null) {
					BigDecimal step_number = new BigDecimal(step_num);
					BigDecimal energy_currency = step_number.divide(
							new BigDecimal(100), BigDecimal.ROUND_DOWN);
					if (energy_currency.intValue() > 30) {
						energy_currency = new BigDecimal("30");
					}
					int rel = Db
							.update("update champion_user set energy_currency=energy_currency+"
									+ energy_currency.toString()
									+ ",cool_run_number=cool_run_number+"
									+ step_num.toString()
									+ ",one_cool_run="
									+ step_num.toString()
									+ " where id='"
									+ championUser.getStr("id") + "'");
					if (rel > 0) {
						ChampionUserCurrencyRecord championUserCurrencyRecord = ChampionUserCurrencyRecord.dao
								.set("id", StringUtil.getUUID())
								.set("user_id", championUser.getStr("id"))
								.set("get_date", new Date())
								.set("get_type", "08")
								.set("energy_currency",
										energy_currency.toString())
								.set("type", "02")
								.set("create_by", championUser.getStr("id"))
								.set("create_name",
										championUser.getStr("user_name"))
								.set("create_date", new Date())
								.set("update_by", championUser.getStr("id"))
								.set("update_name",
										championUser.getStr("user_name"))
								.set("update_date", new Date())
								.set("remarks", "小样微跑");
						championUserCurrencyRecord.save();
						map.put("code", 0);
						map.put("msg", "兑换成功");
					} else {
						map.put("code", -1);
						map.put("msg", "数据库错误");
					}
				} else {
					map.put("code", -2);
					map.put("msg", "今日已上传过");
				}
			} else {
				Db.update("update champion_user set cool_run_number=cool_run_number+"
						+ step_num.toString()
						+ " where id='"
						+ championUser.getStr("id") + "'");
				map.put("code", -2);
				map.put("msg", "酷跑数不满足兑换条件");
			}
		} else {
			map.put("code", -1);
			map.put("msg", "用户不存在");
		}
		JSONObject jsonObj = new JSONObject(map);
		renderJson(callback + "(" + jsonObj.toString() + ")");
		// forwardAction("/home/homePage");
	}

	// 识别路口 该路口是小样官微使用
	@Clear
	public void forwardHome() {
		render("forward.html");
	}

	// 获取微博运动
	public void getWbRun() {
		Map map = new HashMap();
		String dateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
		String xy_openid = getCookie("xy_openid");
		String access_token = getCookie("access_token");
		String content = getPara("content");
		String pic = getPara("pic");
		// try {
		if (!StringUtil.isEmpty(xy_openid)) {
			String result = "sss";
			// String result = Upload.uploadWb(pic, access_token, content);
			if (!StringUtil.isEmpty(result)) {
				String stepStr = getPara("step");

				int step = 0;
				if (!StringUtil.isEmpty(stepStr)) {
					step = Integer.parseInt(stepStr);
				}
				ChampionUser championUser = ChampionUser.dao
						.findFirst("select * from champion_user where wb_id='"
								+ xy_openid + "'");
				if (championUser != null) {
					ChampionUserRun checkUserRun = ChampionUserRun.dao
							.findFirst("select * from champion_user_run where user_id='"
									+ championUser.getStr("id")
									+ "' and get_date='" + dateStr + "'");
					if (checkUserRun == null) {
						ChampionUserRun championUserRun = ChampionUserRun.dao
								.set("id", StringUtil.getUUID())
								.set("get_date", dateStr)
								.set("user_id", championUser.getStr("id"))
								.set("step_number", step)
								.set("ip_address",
										IpKit.getRealIp(getRequest()))
								.set("create_by", championUser.getStr("id"))
								.set("create_name",
										championUser.getStr("user_name"))
								.set("create_date", new Date())
								.set("update_by", championUser.getStr("id"))
								.set("update_name",
										championUser.getStr("user_name"))
								.set("update_date", new Date())
								.set("remarks", "获取微博运动");
						boolean sucess = championUserRun.save();
						if (sucess) {
							int rel = Db
									.update("update champion_user set step_number=step_number+"
											+ step
											+ ",total_step_number=total_step_number+"
											+ step
											+ " where id='"
											+ championUser.getStr("id") + "'");
							int chang_currency = 0;
							int stepNumber = championUser.getInt("step_number")
									+ step;
							if (stepNumber > 0) {
								BigDecimal step_number = new BigDecimal(
										stepNumber);
								BigDecimal energy_currency = step_number
										.divide(new BigDecimal(200),
												BigDecimal.ROUND_DOWN);
								chang_currency = energy_currency.intValue();
							}
							map.put("step_number", stepNumber);
							map.put("chang_currency", chang_currency);
							map.put("code", 0);
							map.put("msg", "成功获取微博运动");

						} else {
							map.put("code", -3);
							map.put("msg", "系统繁忙 请稍后再试");
						}

					} else {

						map.put("code", -1);
						map.put("msg", "今天已获取过微博运动");
					}
				} else {
					map.put("code", -2);
					map.put("msg", "用户不存在");

				}
			} else {
				map.put("code", -3);
				map.put("msg", "系统繁忙 请稍后再试");

			}

		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
		/*
		 * } catch (IOException e) { map.put("code", -3); map.put("msg",
		 * "系统繁忙 请稍后再试"); e.printStackTrace(); renderJson(map); }
		 */

	}

	// 获取活力币记录
	public void getCurrencyEecord() {
		String xy_openid = getCookie("xy_openid");
		String is_page = getPara("is_page"); // 是否分页 0 是
		String page = getPara("page");
		if (StringUtil.isEmpty(page)) {
			page = "1";
		}
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				setAttr("championUser", championUser);
				Page<ChampionUserCurrencyRecord> currencyRecord = ChampionUserCurrencyRecord.dao
						.paginate(
								Integer.parseInt(page),
								10,
								"select *",
								" from champion_user_currency_record where user_id='"
										+ championUser.getStr("id")
										+ "' and type='02' order by get_date desc ");
				if (StringUtil.isEqual(is_page, "1")) {
					renderJson(currencyRecord);
				} else {
					setAttr("currencyRecordList", currencyRecord.getList());
					setAttr("pageNumber", currencyRecord.getPageNumber());
					setAttr("totalPage", currencyRecord.getTotalPage());
					render("record.html");
				}
			}
		} else {
			render("error.html");
		}

	}

	// 用户留言
	public void userMessage() {
		String xy_openid = getCookie("xy_openid");
		String message = getPara("message");
		String access_token = getCookie("accessToken");
		String content = getPara("content");
		String pic = getPara("pic");
		String dateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
		Map map = new HashMap();
		if (!StringUtil.isEmpty(xy_openid) && !StringUtil.isEmpty(access_token)) {
			if (!StringUtil.isEmpty(message) || message == "") {
				ChampionUser championUser = ChampionUser.dao
						.findFirst("select * from champion_user where wb_id='"
								+ xy_openid + "'");
				if (championUser != null) {
					List<ChampionUserMessage> ChampionUserMessageList = ChampionUserMessage.dao
							.find("select * from champion_user_message where user_id='"
									+ championUser.getStr("id")
									+ "' and message_date='" + dateStr + "' ");
					if (ChampionUserMessageList.size() < 20) {
						content = content.replaceAll("用户留言内容", message);
						try {
							Upload.uploadWb(pic, access_token, content);// 发微博
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							ChampionUserMessage championUserMessage = ChampionUserMessage.dao
									.set("id", StringUtil.getUUID())
									.set("user_id", championUser.getStr("id"))
									.set("user_message",
											URLEncoder.encode(message))
									.set("message_date", dateStr)
									.set("create_by", championUser.getStr("id"))
									.set("create_name",
											championUser.getStr("user_name"))
									.set("create_date", new Date())
									.set("update_by", championUser.getStr("id"))
									.set("update_name",
											championUser.getStr("user_name"))
									.set("update_date", new Date());
							championUserMessage.save();
							map.put("code", 0);
							map.put("msg", "留言成功");
						}
					} else {
						map.put("code", -4);
						map.put("msg", "每天留言限制20条");
					}
				} else {
					map.put("code", -1);
					map.put("msg", "用户不存在");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "留言不能为空");
			}
		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
	}

	// 获取明星信息
	public void getStartList() {
		String xy_openid = getCookie("xy_openid");
		String is_page = getPara("is_page"); // 查看排行
		if (!StringUtil.isEmpty(xy_openid)) {
			String is_chang = "0";
			int week_index = DateUtil.dayOfWeek(new Date());
			boolean is_mon_rang = DateUtil.isTimeRang("00:00", "08:00");
			if ((week_index == 2 && is_mon_rang)) {
				is_chang = "1";
			}

			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			setAttr("championUser", championUser);
			setAttr("is_chang", is_chang);
			setAttr("server_uri", PropKit.get("server_uri"));
			if (StringUtil.isEqual(is_page, "1")) {
				String orderBy = " order by energy_currency desc ";
				if (StringUtil.isEqual(is_chang, "1")) {
					orderBy = " order by flower_num desc ";
				}
				List<ChampionStartList> championStartList = ChampionStartList.dao
						.find("select @rownum:=@rownum+1 AS rownum,id,start_head_pic,start_name,energy_currency,energy_percent,flower_num "
								+ " from (SELECT @rownum:=0) r, champion_start_list where 1=1 "
								+ orderBy + " ");
				renderJson(championStartList);
			} else if (StringUtil.isEqual(is_page, "2")) {
				List<ChampionStartList> championStartList = ChampionStartList.dao
						.find("select id,start_head_pic,start_name,energy_currency,energy_percent,flower_num from champion_start_list ORDER BY CONVERT( start_name USING gbk ) COLLATE gbk_chinese_ci ASC   ");
				renderJson(championStartList);

			} else {
				List<ChampionStartList> championStartList = ChampionStartList.dao
						.find("select id,start_head_pic,start_name,energy_currency,energy_percent,flower_num from champion_start_list ORDER BY CONVERT( start_name USING gbk ) COLLATE gbk_chinese_ci ASC   ");
				setAttr("championStartList", championStartList);
				render("champions.html");
			}
		} else {
			render("error.html");
		}
	}

	// 给明星加能
	public void startAddEnergy() {
		Map map = new HashMap();
		String xy_openid = getCookie("xy_openid");
		String start_id = getPara("start_id");
		int energy_currency = 0;
		String pay_currency = getPara("pay_currency");
		String content = getPara("content");
		String access_token = getCookie("accessToken");
		String pic = getPara("pic");
		String is_chang = "0";
		int week_index = DateUtil.dayOfWeek(new Date());
		boolean is_mon_rang = DateUtil.isTimeRang("00:00", "08:00");
		if ((week_index == 2 && is_mon_rang)) {
			is_chang = "1";
		}
		if (!StringUtil.isEmpty(xy_openid) && !StringUtil.isEmpty(access_token)) {
			if (StringUtil.isEqual(is_chang, "0")) {
				if (!StringUtil.isEmpty(pay_currency)) {
					energy_currency = Integer.parseInt(pay_currency);
					ChampionUser championUser = ChampionUser.dao
							.findFirst("select * from champion_user where wb_id='"
									+ xy_openid + "'");
					if (championUser != null) {
						ChampionStartList championStartList = ChampionStartList.dao
								.findById(start_id);
						if (championStartList != null) {
							if (championUser.getInt("energy_currency") >= energy_currency) {
								try {
									ChampionStartCurrencyRecord cscr = ChampionStartCurrencyRecord.dao
											.findFirst("SELECT * FROM champion_start_currency_record WHERE user_id='"
													+ championUser.getStr("id")
													+ "' AND DATE(add_date)=DATE(NOW())");
									if (cscr == null) {
										content = content.replace("start_name",
												championStartList
														.getStr("start_name"));
										content = content.replace("encurry",
												energy_currency + "");
										Upload.uploadWb(pic, access_token,
												content);// 发微博
									}
								} catch (IOException e) {
									e.printStackTrace();
								} finally {
									int res = Db
											.update("update champion_user set energy_currency=energy_currency-"
													+ energy_currency
													+ " where id='"
													+ championUser.getStr("id")
													+ "' ");
									if (res > 0) {
										ChampionStartCurrencyRecord championStartCurrencyRecord = ChampionStartCurrencyRecord.dao
												.set("id", StringUtil.getUUID())
												.set("user_id",
														championUser
																.getStr("id"))
												.set("add_date", new Date())
												.set("start_id", start_id)
												.set("energy_currency",
														energy_currency)
												.set("create_by",
														championUser
																.getStr("id"))
												.set("create_name",
														championUser
																.getStr("user_name"))
												.set("create_date", new Date())
												.set("update_by",
														championUser
																.getStr("id"))
												.set("update_name",
														championUser
																.getStr("user_name"))
												.set("update_date", new Date())
												.set("remarks", "明星加能");
										boolean success = championStartCurrencyRecord
												.save();
										if (success) {
											Db.update("update champion_start_list set energy_currency=energy_currency+"
													+ energy_currency
													+ " where id='"
													+ start_id
													+ "' ");
											ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
													.set("id",
															StringUtil
																	.getUUID())
													.set("user_id",
															championUser
																	.getStr("id"))
													.set("get_date", new Date())
													.set("get_type", "11")
													.set("energy_currency",
															energy_currency)
													.set("type", "01")
													.set("create_by",
															championUser
																	.getStr("id"))
													.set("create_name",
															championUser
																	.getStr("user_name"))
													.set("create_date",
															new Date())
													.set("update_by",
															championUser
																	.getStr("id"))
													.set("update_name",
															championUser
																	.getStr("user_name"))
													.set("update_date",
															new Date())
													.set("remarks", "明星加能");
											boolean is_success = currencyRecord
													.save();
											if (is_success) {
												map.put("code", 0);
												map.put("msg", "恭喜你，加能成功");
												map.put("myEnergyCurrency",
														championUser
																.getInt("energy_currency")
																- energy_currency);
												map.put("startEnergyCurrency",
														championStartList
																.getInt("energy_currency")
																+ energy_currency);
											} else {
												map.put("code", -1);
												map.put("msg", "系统繁忙 请稍后再试");
											}
										}
									}
								}
							} else {
								map.put("code", -3);
								map.put("msg", "活力币不足");
							}
						} else {
							map.put("code", -1);
							map.put("msg", "系统繁忙 请稍后再试");
						}

					} else {
						map.put("code", -2);
						map.put("msg", "用户不存在");
					}
				} else {
					map.put("code", -1);
					map.put("msg", "系统繁忙 请稍后再试");
				}
			} else {
				map.put("code", -5);
				map.put("msg", "时间已过");
			}

			renderJson(map);
		} else {
			render("error.html");
		}
	}

	// 跳转到抢活力币红包页面
	@Clear
	public void forwardSnatch() {
		String xy_openid = getCookie("xy_openid");
		String page = getPara("page");
		if (StringUtil.isEmpty(page)) {
			page = "1";
		}
		if (StringUtil.isEmpty(xy_openid)) {
			xy_openid = "";
		}
		String is_rob = "0";
		ChampionUser championUser = ChampionUser.dao
				.findFirst("select * from champion_user where wb_id='"
						+ xy_openid + "'");
		if (championUser != null) {
			ChampionRobPocket robPocket = ChampionRobPocket.dao
					.findFirst("select * from champion_rob_pocket a left join champion_pocket b on b.id=a.pocket_id where user_id='"
							+ championUser.getStr("id")
							+ "' and TO_DAYS(NOW()) = TO_DAYS(get_date)");
			if (robPocket != null) {
				is_rob = "1";
			}
			Page<ChampionRobPocket> robPocketPage = ChampionRobPocket.dao
					.paginate(
							Integer.parseInt(page),
							10,
							"select a.get_currency,date_format(a.get_date,'%Y/%m/%d') as 'df_date',date_format(a.get_date,'%H:%i') as 'df_time'",
							" from champion_rob_pocket a  where a.user_id='"
									+ championUser.getStr("id")
									+ "' order by a.get_date desc");
			setAttr("robPockeList", robPocketPage.getList());
			setAttr("totalPage", robPocketPage.getTotalPage());
			setAttr("pageNumber", robPocketPage.getPageNumber());
		}
		ChampionPocket pocket = ChampionPocket.dao
				.findFirst("select * from champion_pocket  order by pocket_status");
		setAttr("pocket", pocket);
		setAttr("championUser", championUser);
		setAttr("is_rob", is_rob);
		render("snatch.html");
	}

	// 抢活力币红包
	@Clear
	public void robSnatch() {
		String xy_openid = getCookie("xy_openid");
		String pocket_id = getPara("pocket_id");
		int get_curry = 0;
		Map map = new HashMap();
		Map callMap = new HashMap();
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			ChampionPocket checkPocket = ChampionPocket.dao
					.findFirst("select *,case when (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(begin_date)) >=0 THEN '1' ELSE '0' END AS 'is_rob' from champion_pocket where id ='"
							+ pocket_id + "' ");
			if (checkPocket != null) {
				if(checkPocket.getInt("surplus_pocket_num") >0 && checkPocket.getInt("surplus_currency") >0){
				int surplus_currency = checkPocket
						.getInt("surplus_currency"); // 剩余活力币
				if (StringUtil.isEqual("01",
						checkPocket.getStr("pocket_status"))) {
					if (StringUtil.isEqual(checkPocket.getStr("is_rob"), "1")) {
						ChampionPocketRandom countPocketRandom = ChampionPocketRandom.dao
								.findFirst("select count(*) as 'count' from champion_pocket_random where pocket_id='"
										+ pocket_id + "'");
						if (countPocketRandom.getLong("count") > 0) {
							WbVar key = WbVar.dao
									.findFirst("select * from wb_var where VAR_NAME='currency_pocket_num' ");
							String turntable_prize_num = key
									.getStr("VAR_VALUE"); // 奖品数量
							WbVar gl_key = WbVar.dao
									.findFirst("select * from wb_var where VAR_NAME='rob_pocket_gv' ");
							String turntable_gv = gl_key.getStr("VAR_VALUE");// 转盘概率
							BigDecimal win_num = new BigDecimal(
									turntable_prize_num);
							win_num = win_num.multiply(new BigDecimal(
									turntable_gv));
							int random_num = Integer
									.parseInt(turntable_prize_num);
							int random = RandomUtils.nextInt(1, random_num + 1);
							System.out.println("随机数:"+random);
							if (random <= win_num.intValue()) {
								ChampionPocketRandom pocketRandom = ChampionPocketRandom.dao
										.findFirst("select * from champion_pocket_random where pocket_id='"
												+ pocket_id
												+ "' ORDER BY RAND() LIMIT 1");
								if(pocketRandom != null){
								get_curry = pocketRandom.get("currency_num");
								ChampionPocketRandom.dao
								.deleteById(pocketRandom.get("id"));
								surplus_currency = surplus_currency - get_curry;
								System.out.println("剩余活力币:"+surplus_currency);
								if(surplus_currency >= 0){
								Db.update("update champion_user set energy_currency=energy_currency +"
										+ get_curry
										+ " where id ='"
										+ championUser.getStr("id") + "'");
								String updateSql = "update champion_pocket set surplus_currency=surplus_currency-"
										+ get_curry
										+ ",surplus_pocket_num=surplus_pocket_num-1 where id ='"
										+ pocket_id + "' and surplus_currency -"+get_curry+" >= 0 ";
								if (countPocketRandom.getLong("count") == 1 || surplus_currency == 0) {
									updateSql = "update champion_pocket set surplus_currency=surplus_currency-"
											+ get_curry
											+ ",surplus_pocket_num=surplus_pocket_num-1,pocket_status='02',loot_all_date=now() where id ='"
											+ pocket_id + "' and surplus_currency -"+get_curry+" >= 0 ";
								}
								int scuess=Db.update(updateSql);
								System.out.println(scuess);
								ChampionRobPocket robPocket = ChampionRobPocket.dao
										.set("id", StringUtil.getUUID())
										.set("user_id",
												championUser.getStr("id"))
										.set("pocket_id", pocket_id)
										.set("get_currency",
												get_curry)
										.set("get_date", new Date())
										.set("create_by",
												championUser.getStr("id"))
										.set("create_name",
												championUser
														.getStr("user_name"))
										.set("create_date", new Date())
										.set("update_by",
												championUser.getStr("id"))
										.set("update_name",
												championUser
														.getStr("user_name"))
										.set("update_date", new Date())
										.set("remarks", "抢活力币红包");
								robPocket.save();
								ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
										.set("id", StringUtil.getUUID())
										.set("user_id",
												championUser.getStr("id"))
										.set("get_date", new Date())
										.set("get_type", "09")
										.set("energy_currency",
												get_curry)
										.set("type", "02")
										.set("create_by",
												championUser.getStr("id"))
										.set("create_name",
												championUser
														.getStr("user_name"))
										.set("create_date", new Date())
										.set("update_by",
												championUser.getStr("id"))
										.set("update_name",
												championUser
														.getStr("user_name"))
										.set("update_date", new Date())
										.set("remarks", "活力币红包");
								currencyRecord.save();
								map.put("code", 0);
								map.put("msg", "");
								callMap.put("get_curry", get_curry);
								callMap.put("surplus_currency",
										surplus_currency);
								callMap.put("df_date", DateUtil.formatDate(
										new Date(), "yyyy/MM/dd"));
								callMap.put("df_time", DateUtil.formatDate(
										new Date(), "HH:mm"));
								map.put("data", callMap);
								}else{
									map.put("code", -4);
									map.put("msg", "谢谢参与");
									callMap.put("surplus_currency",
											surplus_currency);
									map.put("data", callMap);
								}
								}else{
									map.put("code", -4);
									map.put("msg", "谢谢参与");
									callMap.put("surplus_currency",
											surplus_currency);
									map.put("data", callMap);
								}
							} else {
								map.put("code", -4);
								map.put("msg", "谢谢参与");
								callMap.put("surplus_currency",
										surplus_currency);
								map.put("data", callMap);
							}
						} else {
							map.put("code", -4);
							map.put("msg", "活力币已抢完");
							callMap.put("surplus_currency", 0);
							map.put("data", callMap);
						}
					} else {
						map.put("code", -5);
						map.put("msg", "抢活力币时间：21:00");
					}
				} else {
					map.put("code", -4);
					map.put("msg", "活力币已抢完");
					callMap.put("surplus_currency", 0);
					map.put("data", callMap);
				}
				}else{
					map.put("code", -4);
					map.put("msg", "活力币已抢完");
					callMap.put("surplus_currency", 0);
					map.put("data", callMap);
				}
			} else {
				map.put("code", -1);
				map.put("msg", "没有红包可以抢");
			}
		} else {
			map.put("code", -3);
			map.put("msg", "用户不存在");
		}
		renderJson(map);
	}

	// 获取摇一摇
	public void getWbShake() {
		String callback = getPara("jsoncallback");
		String xy_openid = getPara("uid");
		String shake_num = getPara("shake_num");
		Map map = new HashMap();
		ChampionUser championUser = ChampionUser.dao
				.findFirst("select * from champion_user where wb_id='"
						+ xy_openid + "'");
		if (championUser != null) {
			if (new BigDecimal(shake_num).intValue() >= 5) {
				ChampionUserCurrencyRecord checkcurrencyRecord = ChampionUserCurrencyRecord.dao
						.findFirst("select * from champion_user_currency_record where TO_DAYS(NOW())=TO_DAYS(get_date) and user_id = '"
								+ championUser.getStr("id")
								+ "'  and get_type = '10' and type='02'  ");
				if (checkcurrencyRecord == null) {
					BigDecimal shake_number = new BigDecimal(shake_num);
					BigDecimal energy_currency = shake_number.divide(
							new BigDecimal(5), BigDecimal.ROUND_DOWN);
					int rel = Db
							.update("update champion_user set energy_currency=energy_currency+"
									+ energy_currency.toString()
									+ ",shake_number=shake_number+"
									+ shake_num
									+ " where id='"
									+ championUser.getStr("id")
									+ "'");
					if (rel > 0) {
						ChampionUserCurrencyRecord championUserCurrencyRecord = ChampionUserCurrencyRecord.dao
								.set("id", StringUtil.getUUID())
								.set("user_id", championUser.getStr("id"))
								.set("get_date", new Date())
								.set("get_type", "10")
								.set("energy_currency",
										energy_currency.toString())
								.set("type", "02")
								.set("create_by", championUser.getStr("id"))
								.set("create_name",
										championUser.getStr("user_name"))
								.set("create_date", new Date())
								.set("update_by", championUser.getStr("id"))
								.set("update_name",
										championUser.getStr("user_name"))
								.set("update_date", new Date())
								.set("remarks", "摇一摇");
						championUserCurrencyRecord.save();
						map.put("code", 0);
						map.put("msg", "兑换成功");
					} else {
						map.put("code", -1);
						map.put("msg", "数据库错误");
					}
				} else {
					map.put("code", -2);
					map.put("msg", "今日已上传过");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "不满足兑换条件");
			}
		} else {
			map.put("code", -1);
			map.put("msg", "用户不存在");
		}
		JSONObject jsonObj = new JSONObject(map);
		renderJson(callback + "(" + jsonObj.toString() + ")");
	}

	// 个人抢红包记录分页
	public void robPocketPage() {
		String xy_openid = getCookie("xy_openid");
		String page = getPara("page");
		if (StringUtil.isEmpty(page)) {
			page = "1";
		}
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			Page<ChampionRobPocket> robPocketPage = ChampionRobPocket.dao
					.paginate(
							Integer.parseInt(page),
							10,
							"select a.get_currency,date_format(a.get_date,'%Y/%m/%d') as 'df_date',date_format(a.get_date,'%H:%i') as 'df_time'",
							" from champion_rob_pocket a  where a.user_id='"
									+ championUser.getStr("id")
									+ "'  order by a.get_date desc ");
			renderJson(robPocketPage);
		} else {
			render("error.html");
		}

	}

	// 抢红包记录
	public void PocketRecord() {
		String xy_openid = getCookie("xy_openid");
		String page = getPara("page");
		String type = getPara("type");
		String pocket_id = getPara("pocket_id");
		if (StringUtil.isEmpty(page)) {
			page = "1";
		}
		if (!StringUtil.isEmpty(xy_openid)) {
			Page<ChampionRobPocket> robPocketPage = ChampionRobPocket.dao
					.paginate(
							Integer.parseInt(page),
							10,
							"select a.get_currency,date_format(a.get_date,'%H:%i') as 'df_time',c.user_name,c.head_pic ",
							" from champion_rob_pocket a left join champion_pocket b on b.id =a.pocket_id left join champion_user c on c.id=a.user_id where a.pocket_id ='"
									+ pocket_id + "' order by a.get_date desc");
			if (!StringUtil.isEmpty(type)) {
				renderJson(robPocketPage);
			} else {
				setAttr("robPocketList", robPocketPage.getList());
				setAttr("pageNumber", robPocketPage.getPageNumber());
				setAttr("totalPage", robPocketPage.getTotalPage());
				setAttr("pocket_id", pocket_id);
				render("others.html");
			}
		} else {
			render("error.html");
		}

	}

	// 跳转到欧洲杯竞猜页面
	@Clear
	public void forwardEuropeGuessing() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			Map map = new HashMap();
			List<Map> list = new ArrayList<Map>();
			// 赛事
			List<ChampionEuropeCompetition> championCompetitionList = ChampionEuropeCompetition.dao
					.find("select a.*,DATE_FORMAT(DATE_SUB(a.end_time,INTERVAL 45 MINUTE),'%Y.%m.%d %H:%i') as 'begin_time_df',b.team_pic as 'visiting_team_pic',b.team_name as 'visiting_team_name',c.team_pic as 'home_team_pic',c.team_name as 'home_team_name',d.key_value as 'competition_type_name',CASE  WHEN (UNIX_TIMESTAMP(a.end_time)-UNIX_TIMESTAMP(NOW())) >0 THEN '1' ELSE '0' END AS 'is_guess' ,TIMESTAMPDIFF(SECOND,now(),a.end_time) as 'guess_second' from champion_europe_competition a left join champion_europe_team c on c.id=a.home_team left join champion_europe_team b on b.id=a.visiting_team left join wb_key d on d.key_name =a.competition_type where competition_status <>'05'  and d.key_type='champion_europe_team.competition_type' and d.key_is_leaf='1' AND TO_DAYS(NOW()) BETWEEN TO_DAYS(a.begin_time) AND TO_DAYS(a.end_time) order by a.competition_status,a.end_time");
			if (championCompetitionList != null) {
				if (championCompetitionList.size() > 0) {
					for (int i = 0; i < championCompetitionList.size(); i++) {
						Map dataMap = new HashMap();
						ChampionEuropeCompetition championCompetition = championCompetitionList
								.get(i);
						dataMap.put("championCompetition", championCompetition);
						BigDecimal expect_energy_currency = new BigDecimal("0");
						if (championUser != null) {
							ChampionEuropeGuessing championUserGuessing = ChampionEuropeGuessing.dao
									.findFirst("select pay_currency,win_currency ,competition_result from champion_europe_guessing where user_id='"
											+ championUser.getStr("id")
											+ "' and competition_id='"
											+ championCompetition.getStr("id")
											+ "'");
							dataMap.put("championUserGuessing",
									championUserGuessing);
							setAttr("championUserGuessing",
									championUserGuessing);
							MathContext mc = new MathContext(2);
							if (championUserGuessing != null) {
								if(!StringUtil.isEmpty(championCompetition.getStr("winner"))){
								if(StringUtil.isEqual(championCompetition.getStr("winner"), championUserGuessing.getStr("competition_result"))){
									expect_energy_currency = expect_energy_currency
											.add(championCompetition
													.getBigDecimal("home_odds"));
									expect_energy_currency = expect_energy_currency
											.multiply(new BigDecimal(
													championUserGuessing
															.getInt("pay_currency")));
								}
								
								}else{
									expect_energy_currency = expect_energy_currency
											.add(championCompetition
													.getBigDecimal("home_odds"));
									expect_energy_currency = expect_energy_currency
											.multiply(new BigDecimal(
													championUserGuessing
															.getInt("pay_currency")));
								}

							}
							dataMap.put("expect_energy_currency",
									expect_energy_currency);
						}
						list.add(dataMap);
					}
				}
				map.put("championCompetitionList", list);
			}
			setAttr("championCompetitionList", list);
			setAttr("server_uri", PropKit.get("server_uri"));
			setAttr("championUser", championUser);
			renderJson(map);
			render("football.html");
		} else {
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			render("error.html");
		}

	}

	// 欧洲杯赛事竞猜
	public void guessEuropeCompetition() {
		Map map = new HashMap();
		String competition_id = getPara("competition_id");
		String xy_openid = getCookie("xy_openid");
		int pay_currency = getParaToInt("pay_currency");
		String pay_odds = getPara("pay_odds");
		String team_type = getPara("team_type");
		String access_token = getCookie("accessToken");
		String competition_result = getPara("competition_result");
		String content = getPara("content");
		String pic = getPara("pic");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				if (championUser.getInt("energy_currency") >= pay_currency) {
					ChampionEuropeCompetition championCompetition = ChampionEuropeCompetition.dao
							.findFirst("select a.*,c.team_name as 'home_team_name',d.team_name as 'visit_team_name',b.key_value ,(UNIX_TIMESTAMP(end_time)-UNIX_TIMESTAMP(NOW())) AS 'is_guess' from champion_europe_competition a left join wb_key b on b.key_name=a.competition_type left join champion_europe_team c on c.id=a.home_team left join champion_europe_team d on d.id=a.visiting_team  where a.competition_status='01' and b.key_type='champion_europe_team.competition_type' and b.key_is_leaf='1' and a.id='"
									+ competition_id + "' ");
					if (championCompetition != null) {
						if (championCompetition.getLong("is_guess") > 0) {
							ChampionEuropeGuessing checkUserGuessing = ChampionEuropeGuessing.dao
									.findFirst("select * from champion_europe_guessing where competition_id='"
											+ competition_id
											+ "' and  user_id='"
											+ championUser.getStr("id") + "'");
							if (checkUserGuessing == null) {
								String result="";
								WbKey key=WbKey.dao.findFirst("select * from wb_key where key_type='champion_europe_guessing.competition_result' and key_is_leaf='1' and key_name='"+competition_result+"'");
								if(key != null ){
									result=key.getStr("key_value");
								}
								String competition_name=championCompetition.getStr("key_value")+championCompetition.getStr("home_team_name")+"vs"+championCompetition.getStr("visit_team_name");
								content=content.replaceAll("competition", competition_name);
								content=content.replaceAll("result", result);
								System.out.println(content);
									String id = StringUtil.getUUID();
									ChampionEuropeGuessing championUserGuessing = ChampionEuropeGuessing.dao
											.set("id", id)
											.set("user_id",
													championUser.getStr("id"))
											.set("competition_id", competition_id)
											.set("team_id", "")
											.set("guess_date", new Date())
											.set("pay_odds", pay_odds)
											.set("pay_currency", pay_currency)
											.set("team_type", "")
											.set("guess_status", "01")
											.set("competition_result",
													competition_result)
											.set("create_by",
													championUser.getStr("id"))
											.set("create_name",
													championUser
															.getStr("user_name"))
											.set("create_date", new Date())
											.set("update_by",
													championUser.getStr("id"))
											.set("update_name",
													championUser
															.getStr("user_name"))
											.set("update_date", new Date())
											.set("remarks", "欧洲杯竞猜");
									boolean is_sucess = championUserGuessing.save();
									int remain_energy_currency = championUser
											.getInt("energy_currency")
											- pay_currency;
									if (is_sucess) {
										BigDecimal get_energy_currency = new BigDecimal(
												pay_currency);
											get_energy_currency = get_energy_currency
													.multiply(new BigDecimal(pay_odds));
										Db.update("update champion_user set energy_currency=energy_currency-"
												+ pay_currency
												+ " where id='"
												+ championUser.getStr("id") + "'");
										ChampionUserCurrencyRecord currencyRecord = ChampionUserCurrencyRecord.dao
												.set("id", StringUtil.getUUID())
												.set("user_id",
														championUser.getStr("id"))
												.set("get_date", new Date())
												.set("get_type", "12")
												.set("energy_currency",
														pay_currency)
												.set("type", "01")
												.set("create_by",
														championUser.getStr("id"))
												.set("create_name",
														championUser
																.getStr("user_name"))
												.set("create_date", new Date())
												.set("update_by",
														championUser.getStr("id"))
												.set("update_name",
														championUser
																.getStr("user_name"))
												.set("update_date", new Date())
												.set("remarks", "周日竞猜消费");
										currencyRecord.save();
										Map dataMap = new HashMap();
										map.put("code", 0);
										map.put("msg", "竞猜成功");
										dataMap.put("remain_energy_currency",
												remain_energy_currency);
										dataMap.put("get_energy_currency",
												get_energy_currency);
										map.put("callBackData", dataMap);
									} else {
										map.put("code", -3);
										map.put("msg", "系统繁忙 请稍后再试");
									}

							} else {
								map.put("code", -1);
								map.put("msg", "已竞猜过");
							}
						} else {
							map.put("code", -3);
							map.put("msg", "下注时间已过，无法竞猜");
						}
					} else {
						map.put("code", -4);
						map.put("msg", "该赛事无法竞猜");
					}
				} else {
					map.put("code", -4);
					map.put("msg", "活力币不足");
				}
			} else {
				map.put("code", -2);
				map.put("msg", "用户不存在");
			}
			renderJson(map);
		} else {
			String url=getRequest().getRequestURI();
			setAttr("url", url.substring(url.indexOf("xyOlympic_wx")+13, url.length()));
			render("error.html");
		}
		
	}

	// 跳转到欧洲杯冠军竞猜页面
	public void forwardEuropeWinnerGuessing() {
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				WbVar var = WbVar.dao
						.findFirst("select * from wb_var where VAR_NAME='win_end_time' ");
				if (var != null) {
					Date end_date = DateUtil.stringToDate(
							var.getStr("VAR_VALUE"), "yyyy-MM-dd HH:mm");
					Date curry_date = new Date();
					int is_over=0;//否
					if (end_date.getTime() - curry_date.getTime() > 0) {
						is_over=1;
					}
					    setAttr("is_over", is_over);
						List<ChampionEuropeTeam> europeTeamList = ChampionEuropeTeam.dao
								.find("select * from champion_europe_team where team_status='01'");
						setAttr("europeTeamList", europeTeamList);
						int is_guess = 0;//否
						ChampionWinnerGuessing checkGuessing = ChampionWinnerGuessing.dao
								.findFirst("select * from champion_winner_guessing where user_id='"
										+ championUser.getStr("id") + "'");
						if (checkGuessing != null) {
							is_guess = 1;
						}
						setAttr("is_guess", is_guess);
				}
			}
		} else {
			render("error.html");
		}

	}

	// 欧洲杯冠军竞猜
	public void guessEuropeWinner() {
		Map map = new HashMap();
		String team_id = getPara("team_id");
		String xy_openid = getCookie("xy_openid");
		if (!StringUtil.isEmpty(xy_openid)) {
			ChampionUser championUser = ChampionUser.dao
					.findFirst("select * from champion_user where wb_id='"
							+ xy_openid + "'");
			if (championUser != null) {
				WbVar var = WbVar.dao
						.findFirst("select * from wb_var where VAR_NAME='win_end_time' ");
				if (var != null) {
					Date end_date = DateUtil.stringToDate(
							var.getStr("VAR_VALUE"), "yyyy-MM-dd HH:mm");
					Date curry_date = new Date();
					if (end_date.getTime() - curry_date.getTime() > 0) {
						ChampionWinnerGuessing checkGuessing = ChampionWinnerGuessing.dao
								.findFirst("select * from champion_winner_guessing where user_id='"
										+ championUser.getStr("id") + "'");
						if (checkGuessing == null) {
							ChampionEuropeTeam europeTeam = ChampionEuropeTeam.dao
									.findById(team_id);
							if (europeTeam != null) {
								if (StringUtil.isEqual(
										europeTeam.getStr("team_status"), "01")) {
									ChampionWinnerGuessing winnerGuessing = ChampionWinnerGuessing.dao
											.set("id", StringUtil.getUUID())
											.set("user_id",
													championUser.get("id"))
											.set("team_id", team_id)
											.set("guess_date", new Date())
											.set("create_by",
													championUser.getStr("id"))
											.set("create_name",
													championUser
															.getStr("user_name"))
											.set("create_date", new Date())
											.set("update_by",
													championUser.getStr("id"))
											.set("update_name",
													championUser
															.getStr("user_name"))
											.set("update_date", new Date())
											.set("remarks", "欧洲杯冠军竞猜");
									winnerGuessing.save();
									map.put("code", 0);
									map.put("msg", "竞猜成功");
								} else {
									map.put("code", -1);
									map.put("msg", "球队已淘汰");
								}
							} else {
								map.put("code", -2);
								map.put("msg", "球队不存在");
							}
						} else {
							map.put("code", -3);
							map.put("msg", "已竞猜过");
						}
					} else {
						map.put("code", -4);
						map.put("msg", "竞猜时间已过");
					}
				}
			}
		} else {
			map.put("code", 404);
			map.put("msg",
					"https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI") + "");
		}
		renderJson(map);
	}
	    // 分享添加活力币
		public void shareAdd() {
			String xy_openid = getCookie("xy_openid");
			String share_type = getPara("share_type");
			String dateStr = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
			Map map = new HashMap();
			if (!StringUtil.isEmpty(xy_openid)) {
				ChampionUser championUser = ChampionUser.dao
						.findFirst("select * from champion_user where wb_id='"
								+ xy_openid + "'");
				if (championUser != null) {
					ChampionUserShare checkUserShare=ChampionUserShare.dao.findFirst("select * from champion_user_share where user_id='"+championUser.getStr("id")+"' and share_date='"+dateStr+"' and share_type='"+share_type+"'");
					if(checkUserShare == null){
					Db.update("update champion_user set energy_currency=energy_currency+100 where id='"
							+ championUser.getStr("id") + "'");
					ChampionUserShare championUserShare=ChampionUserShare.dao.set("id", StringUtil.getUUID())
							.set("user_id", championUser.getStr("id"))
							.set("share_date", dateStr)
							.set("share_type", share_type)
							.set("create_by",
									championUser.getStr("id"))
							.set("create_name",
									championUser
											.getStr("user_name"))
							.set("create_date", new Date())
							.set("update_by",
									championUser.getStr("id"))
							.set("update_name",
									championUser
											.getStr("user_name"))
							.set("update_date", new Date())
							.set("remarks", "分享");
					championUserShare.save();
					}
					map.put("code", 0);
					map.put("msg", "成功");
					renderJson(map);
				}
			} else {
				render("error.html");
			}
		}
		
		//清除缓存
		@Clear
	   public void clearCookie(){
			setCookie("wbUid", null, 0, "/");
			renderNull();
		}
}
